package com.frame.platform.user;

import java.util.*;

import org.hibernate.*;

import com.frame.database.*;
import com.frame.database.util.*;
import com.frame.hibernate.HibernateUtil;
import com.frame.platform.dept.Wfdept;
import com.frame.platform.post.PostBean;
import com.frame.util.MD5;

public class UserDao {

	public UserDao(){

	}

	public PageResult getUserList(String userName,String loginName,String deptId,int size,int pageNo) throws Exception{
		ConditionMap map=new ConditionMap();
		map.put("state<>2");
		map.put("usertype=1");
		map.put("userid<>'0000000001'");
		if(deptId!=null && !deptId.equals(""))
			map.put("userid in (select d.id.userid from Wfuserdept d where d.id.deptid=?)").setParameter(new Object[]{deptId});
		if(userName!=null && !"".equals(userName))
			map.put("(username like ? or loginname like ?)").setParameter(new Object[]{"%"+userName+"%","%"+userName+"%"});
		map.addOrder("userid", true);
		PageResult pr=DataBase.getInstance().query("Wfuser", map,size,pageNo);
		return pr;
	}


	public List<PostBean> getUserPost(String uid) throws Exception{
		String sql="select p.* from WFPOST p,wfuserpost pu where pu.postid=p.id and pu.userid=? order by p.orderid";
		return DbOperate.getInstance().query(sql, new Object[]{uid}, PostBean.class);
	}

	public List getUserIds(String deptId) throws Exception{
		return DataBase.getInstance().queryBySql("select userid from Wfuser where state=1", null);
	}
	public void addUser(Wfuser user,String[] deptId) throws HibernateException, Exception{
//		DataBase database=DataBase.getInstance();
//		user.setUserid(null);
//		user.setUserpwd(new MD5().getMD5ofStr(user.getUserpwd()));
//		user.setState(new Integer(1));
//		user.setUsertype(new Integer(1));
//		user.setRegTime(new Date());
//		database.save(user);
		JdataBean bean=new JdataBean();
		bean.put("userid", new Seq().getKeyId("Wfusernid"));
		bean.put("Userpwd", new MD5().getMD5ofStr(user.getUserpwd()));
		bean.put("State", 1);
		bean.put("Usertype", 1);
		bean.put("Email", user.getEmail());
		bean.put("Username", user.getUsername());
		bean.put("Loginname", user.getLoginname());
		bean.put("Sex", user.getSex());
		bean.put("Mobile", user.getMobile());
		bean.put("Qq", user.getQq());
		bean.put("Phone", user.getPhone());
		bean.put("Address", user.getAddress());
		bean.put("RegTime", new Date());
		DbOperate db=DbOperate.getInstance();
		db.saveBean("Wfuser", bean.getDataMap());
		for(int i=0;i<deptId.length;i++){
			WfuserdeptId id=new WfuserdeptId(user.getUserid(),deptId[i]);
			Wfuserdept userdept=new Wfuserdept();
			userdept.setId(id);
//			database.save(userdept);
			Map dataMap=new HashMap();
			dataMap.put("USERID", bean.getString("userid"));
			dataMap.put("DEPTID", deptId[i]);
			db.saveBean("wfuserdept", dataMap);
		}
	}
	public void updateUser(Wfuser user,String[] deptId) throws Exception{
		Session session=HibernateUtil.currentSession();
		Wfuser olduser=(Wfuser)session.load(Wfuser.class, user.getUserid());
		olduser.setUsername(user.getUsername());
		olduser.setLoginname(user.getLoginname());
		olduser.setSex(user.getSex());
		olduser.setAddress(user.getAddress());
		olduser.setQq(user.getQq());
		olduser.setPhone(user.getPhone());
		olduser.setEmail(user.getEmail());
		olduser.setMobile(user.getMobile());
		session.flush();
		HibernateUtil.closeSession();
		DataBase database=DataBase.getInstance();
		database.delete("Wfuserdept", "userid", user.getUserid());
		for(int i=0;i<deptId.length;i++){
			JdataBean bean=new JdataBean();
			bean.put("userid", user.getUserid());
			bean.put("deptid", deptId[i]);
			DbOperate.getInstance().saveBean("Wfuserdept", bean.getDataMap());
		}
	}
	public void updataPwd(String userid,String newpwd){
		Session session=HibernateUtil.currentSession();
		Transaction transaction=session.beginTransaction();
		Wfuser olduser=(Wfuser)session.load(Wfuser.class, userid);
		olduser.setUserpwd(new MD5().getMD5ofStr(newpwd));
		session.flush();
		transaction.commit();
		HibernateUtil.closeSession();
	}


	public boolean checkPwd(String uid,String pwd) throws HibernateException, Exception{
		Wfuser user=getUser(uid);
		String upwd=user.getUserpwd();
		String upwdstr=new MD5().getMD5ofStr(pwd);
		if(upwdstr.equals(upwd))
			return true;
		else
			return false;
	}
	public Wfuser getUser(String userId) throws HibernateException, Exception{
		return (Wfuser) DataBase.getInstance().getBean(Wfuser.class, userId);
	}
	public void delUser(String[] userIds,String deptId) throws Exception{
		DataBase data=DataBase.getInstance();
		if(userIds!=null){
			for(int i=0;i<userIds.length;i++){
				WfuserdeptId id=new WfuserdeptId(userIds[i],deptId);
				Wfuserdept udept=new Wfuserdept();
				udept.setId(id);
				data.delete(udept);
				List list=data.queryBySql("select u from Wfuserdept u where u.id.userid=?", new Object[]{userIds[i]});
				if(list.size()<=1){
					data.update("update Wfuser set state=2 where userid=?", new Object[]{userIds[i]});
				}
			}

		}


	}
	public boolean checkLoginName(String loginName,String userId) throws Exception{
		if(loginName!=null && !"".equals(loginName)){
			ConditionMap map=new ConditionMap();
			map.put("loginname = ?").setParameter(new Object[]{loginName});
			map.put("state <> 2");
			if(userId!=null && !"".endsWith(userId))
				map.put("userid <> ?").setParameter(new Object[]{userId});
			List list=DataBase.getInstance().query("Wfuser", map);
			if(list.size()>0)
				return false;
			else
				return true;
		}
		return true;
	}


	public void updateUserState(String userId,Integer state){
		Session session=HibernateUtil.currentSession();
		Transaction transaction=session.beginTransaction();
		Wfuser olduser=(Wfuser)session.load(Wfuser.class, userId);
		olduser.setState(state);
		session.flush();
		transaction.commit();
		HibernateUtil.closeSession();
	}

	public List<Wfdept> getUserDeptList(String userId) throws Exception{
		return DbOperate.getInstance().query("Select d.*,ud.ISDEFAULT From wfdept d,wfuserdept ud Where d.deptid=ud.deptid And ud.userid=?", new Object[]{userId},Wfdept.class);
	}

	public List getDeptUserList(String deptId) throws Exception{
		ConditionMap map=new ConditionMap();
		map.put("userid <> '0000000001'");
		map.put("userid in (select d.id.userid from Wfuserdept d where d.id.deptid=?) and state=1").setParameter(deptId);
		map.addOrder("userid", true);
		return DataBase.getInstance().query("Wfuser", map);
	}

	public List getRankList(String rankName) throws Exception{
		ConditionMap map=new ConditionMap();
		if(rankName!=null && !"".equals(rankName))
			map.put("rankname like ?").setParameter("%"+rankName+"%");
		return DataBase.getInstance().query("Wfrank", map);
	}

	public List getUserRankList(String userId,String deptId) throws Exception{
		ConditionMap map=new ConditionMap();
		map.put("rankid in (select d.id.rankid from Wfuserrank d where d.id.userid=? and d.id.deptid=?)").setParameter(new Object[]{userId,deptId});
		return DataBase.getInstance().query("Wfrank", map);
	}

	public void addUserRank(String userId,String[] deptIds,String[] rankIds) throws HibernateException, Exception{
		DbOperate db=DbOperate.getInstance();
		for(String depid:deptIds)
			db.update("delete from wfuserrank where userid=? and deptid=?", new Object[]{userId,depid});
		if(rankIds!=null){
			for(String depid:deptIds){
				for(int i=0;i<rankIds.length;i++){
					Map data=new HashMap();
					data.put("userid", userId);
					data.put("deptid", depid);
					data.put("rankid", rankIds[i]);
					db.saveBean("wfuserrank", data);
				}
			}
		}

	}


	public String getDeptName(String deptId) throws HibernateException, Exception{
		DataBase data=DataBase.getInstance();
//		String dname="";
		List list=data.queryBySql("select d from Wfdept d where d.deptid=?", new Object[]{new Integer(deptId)});
		Wfdept dept=(Wfdept)list.get(0);
//		dname=dept.getDeptname();
//		if(!deptId.equals(boardId)){
//			List blist=data.queryBySql("select d from Wfdept d where d.deptid=?", new Object[]{new Integer(boardId)});
//			Wfdept board=(Wfdept)blist.get(0);
//			dname=board.getDeptname()+dname;
//		}
		return dept.getDeptname();
	}
	public List<Wfuser> queryByIds(String[] ids) throws Exception{
		String in="";
		if(ids!=null){
			Object[] parm=new Object[ids.length];
			for(int i=0;i<ids.length;i++){if(!in.equals(""))in+=",";in+="?";parm[i]=ids[i];}
			return DataBase.getInstance().queryBySql("from Wfuser where userid in ("+in+")", parm);
		}return null;
	}
	public PageResult getOnUserList(String userName,int size,int pagno) throws Exception{
		DataBase data=DataBase.getInstance();
		Object[] objpam=null;
		String sql="select u,n from Wfuser u,Wfonlineuser n where u.userid=n.userid";
		if(userName!=null && !"".equals(userName)){
			sql+=" and u.username like ?";
			objpam=new Object[]{"%"+userName+"%"};
		}
		PageResult pr=data.queryBySql(sql, objpam, size, pagno);
		List dlist=new ArrayList();
		for(int i=0;i<pr.getList().size();i++){
			Object[] obj=(Object[])pr.getList().get(i);
			Wfuser user=(Wfuser)obj[0];
			Wfonlineuser on=(Wfonlineuser)obj[1];
			OnUserForm form=new OnUserForm();
			form.setUserid(user.getUserid());
			form.setUsername(user.getUsername());
			form.setDeptName(on.getDeptname());
			form.setLoginTime(on.getLogintime());
			form.setSessionid(on.getSessionid());
			form.setIp(on.getIp());
			dlist.add(form);
		}
		pr.setList(dlist);
		return pr;
	}

	public void clearOnUser() throws Exception{
		DataBase.getInstance().delete("delete Wfonlineuser", null);
	}

	public void addOnUser(String userId,String deptName,String ip,String sessionid){
		DataBase data=DataBase.getInstance();
		try {
			Wfonlineuser onuser = (Wfonlineuser)data.getBean(Wfonlineuser.class, userId);
			if(onuser==null){
				onuser=new Wfonlineuser();
				onuser.setUserid(userId);
				onuser.setDeptname(deptName);
				onuser.setLogintime(new Date());
				onuser.setIp(ip);
				onuser.setSessionid(sessionid);
				data.save(onuser);
			}
			else{
				onuser.setUserid(userId);
				onuser.setDeptname(deptName);
				onuser.setLogintime(onuser.getLogintime());
				onuser.setIp(ip);
				onuser.setSessionid(sessionid);
				data.update(onuser);
			}
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void delOnUser(String sessionId){
		try {
			DataBase.getInstance().delete("Wfonlineuser", "sessionid", sessionId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void writeSysLog(String userid,String title,String content,String ip){
		try{
			JdataBean data=new JdataBean();
			data.put("logtime", new Date().getTime()/1000);
			data.put("title", title);
			data.put("userid", userid);
			data.put("content", content);
			data.put("ip", ip);
			DbOperate.getInstance().saveBean("wf_syslog",data.getDataMap());
		}catch(Exception e){e.printStackTrace();}
	}
}
